<template>
  <PageContainer title="设备管理">
    <!-- 搜索筛选区域 -->
    <SearchForm v-model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-form-item label="设备筛选">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入设备名称或编号"
          clearable
        />
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select
          v-model="searchForm.status"
          placeholder="请选择设备状态"
          clearable
        >
          <el-option label="在线" value="online" />
          <el-option label="离线" value="offline" />
          <el-option label="已满" value="full" />
          <el-option label="故障" value="error" />
          <el-option label="维护中" value="maintenance" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型">
        <el-select
          v-model="searchForm.type"
          placeholder="请选择设备类型"
          clearable
        >
          <el-option label="纸壳类" value="paper" />
          <el-option label="织物类" value="textile" />
          <el-option label="混合类" value="mixed" />
        </el-select>
      </el-form-item>
      <el-form-item label="安装地点">
        <el-input
          v-model="searchForm.location"
          placeholder="请输入安装地点"
          clearable
        />
      </el-form-item>
      <el-form-item label="安装时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>



    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button
          type="primary"
          @click="handleAddDevice"
        >
          <el-icon><Plus /></el-icon>
          新增设备
        </el-button>

        <el-button
          type="info"
          @click="handleExport"
        >
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
      <div class="action-right">
        <el-button
          type="info"
          @click="loadDeviceList"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 设备列表表格 -->
    <DataTable
      :data="deviceList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="设备ID" width="80" />
      <el-table-column label="设备信息" width="200">
        <template #default="{ row }">
          <div class="device-info">
            <div class="device-name">{{ row.name }}</div>
            <div class="device-code">{{ row.code }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTypeTag(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" width="100">
        <template #default="{ row }">
          <DeviceStatus :status="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="安装地点" min-width="200">
        <template #default="{ row }">
          <div class="text-ellipsis">{{ row.location }}</div>
        </template>
      </el-table-column>
      <el-table-column label="容量信息" width="120">
        <template #default="{ row }">
          <div class="capacity-info">
            <div class="capacity-text">{{ row.currentCapacity }}/{{ row.maxCapacity }}kg</div>
            <el-progress
              :percentage="getCapacityPercentage(row)"
              :color="getCapacityColor(row)"
              :show-text="false"
              :stroke-width="4"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="今日投递" width="100" sortable>
        <template #default="{ row }">
          {{ row.todayDisposals }}
        </template>
      </el-table-column>
      <el-table-column label="累计投递" width="100" sortable>
        <template #default="{ row }">
          {{ row.totalDisposals }}
        </template>
      </el-table-column>
      <el-table-column label="安装时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.installedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="最后上报" width="180">
        <template #default="{ row }">
          {{ row.lastReportAt ? formatDateTime(row.lastReportAt) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command: string) => handleMoreAction(row, command)">
            <el-button type="text" size="small">
              更多<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="remote-control">远程控制</el-dropdown-item>
                <el-dropdown-item command="maintenance">维护记录</el-dropdown-item>
                <el-dropdown-item command="disposal-records">投递记录</el-dropdown-item>
                <el-dropdown-item command="clear-bin">清空回收箱</el-dropdown-item>
                <el-dropdown-item
                  command="delete"
                  :disabled="row.status === 'online'"
                  divided
                >
                  删除设备
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 设备详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="设备详情"
      width="80%"
    >
      <div v-if="currentDevice" class="device-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="设备ID">
                {{ currentDevice.id }}
              </el-descriptions-item>
              <el-descriptions-item label="设备名称">
                {{ currentDevice.name }}
              </el-descriptions-item>
              <el-descriptions-item label="设备编号">
                {{ currentDevice.code }}
              </el-descriptions-item>
              <el-descriptions-item label="设备类型">
                <el-tag :type="getTypeTag(currentDevice.type)">
                  {{ getTypeText(currentDevice.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="设备状态">
                <DeviceStatus :status="currentDevice.status" />
              </el-descriptions-item>
              <el-descriptions-item label="安装地点">
                {{ currentDevice.location }}
              </el-descriptions-item>
              <el-descriptions-item label="安装时间">
                {{ formatDateTime(currentDevice.installedAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="最后上报">
                {{ currentDevice.lastReportAt ? formatDateTime(currentDevice.lastReportAt) : '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions title="运行数据" :column="1" border>
              <el-descriptions-item label="当前容量">
                {{ currentDevice.currentCapacity }}/{{ currentDevice.maxCapacity }}kg
                ({{ getCapacityPercentage(currentDevice) }}%)
              </el-descriptions-item>
              <el-descriptions-item label="今日投递">
                {{ currentDevice.todayDisposals }}次
              </el-descriptions-item>
              <el-descriptions-item label="累计投递">
                {{ currentDevice.totalDisposals }}次
              </el-descriptions-item>
              <el-descriptions-item label="今日收益">
                ¥{{ currentDevice.todayEarnings }}
              </el-descriptions-item>
              <el-descriptions-item label="累计收益">
                ¥{{ currentDevice.totalEarnings }}
              </el-descriptions-item>
              <el-descriptions-item label="故障次数">
                {{ currentDevice.errorCount }}次
              </el-descriptions-item>
              <el-descriptions-item label="维护次数">
                {{ currentDevice.maintenanceCount }}次
              </el-descriptions-item>
              <el-descriptions-item label="设备评分">
                <el-rate
                  v-model="currentDevice.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>

        <!-- 设备传感器数据 -->
        <div class="sensor-data" style="margin-top: 20px;">
          <h4>传感器数据</h4>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="sensor-card">
                <div class="sensor-item">
                  <div class="sensor-label">温度</div>
                  <div class="sensor-value">{{ currentDevice.temperature }}°C</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="sensor-card">
                <div class="sensor-item">
                  <div class="sensor-label">湿度</div>
                  <div class="sensor-value">{{ currentDevice.humidity }}%</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="sensor-card">
                <div class="sensor-item">
                  <div class="sensor-label">电池电量</div>
                  <div class="sensor-value">{{ currentDevice.batteryLevel }}%</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="sensor-card">
                <div class="sensor-item">
                  <div class="sensor-label">信号强度</div>
                  <div class="sensor-value">{{ currentDevice.signalStrength }}dBm</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 最近投递记录 -->
        <div class="recent-disposals" style="margin-top: 20px;">
          <h4>最近投递记录</h4>
          <el-table :data="currentDevice.recentDisposals" size="small">
            <el-table-column prop="id" label="记录ID" width="100" />
            <el-table-column prop="userName" label="用户" width="120" />
            <el-table-column prop="wasteType" label="垃圾类型" width="100" />
            <el-table-column prop="weight" label="重量(kg)" width="100" />
            <el-table-column prop="earnings" label="收益" width="100">
              <template #default="{ row }">
                ¥{{ row.earnings }}
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="投递时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'success' ? 'success' : 'warning'">
                  {{ row.status === 'success' ? '成功' : '异常' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑设备对话框 -->
    <el-dialog
      v-model="deviceDialogVisible"
      :title="isEdit ? '编辑设备' : '新增设备'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="deviceFormRef"
        :model="deviceForm"
        :rules="deviceRules"
        label-width="100px"
      >
        <el-form-item label="设备编号" prop="code">
          <el-input
            v-model="deviceForm.code"
            placeholder="请输入设备编号"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select
            v-model="deviceForm.type"
            placeholder="请选择设备类型"
            style="width: 100%"
          >
            <el-option label="纸壳类" value="paper" />
            <el-option label="织物类" value="textile" />
            <el-option label="混合类" value="mixed" />
          </el-select>
        </el-form-item>
        <el-form-item label="安装地点" prop="location">
          <el-select
            v-model="deviceForm.location"
            placeholder="请选择安装地点"
            filterable
            style="width: 100%"
            :loading="areaLoading"
          >
            <el-option
              v-for="area in areaOptions"
              :key="area.value"
              :label="area.label"
              :value="area.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="最大容量" prop="maxCapacity">
          <el-input-number
            v-model="deviceForm.maxCapacity"
            :min="1"
            :max="1000"
            placeholder="请输入最大容量"
            style="width: calc(100% - 40px)"
          />
          <span style="margin-left: 8px; color: #909399;">KG</span>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select
            v-model="deviceForm.status"
            placeholder="请选择设备状态"
            style="width: 100%"
          >
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="安装时间">
          <el-date-picker
            v-model="deviceForm.installedAt"
            type="datetime"
            placeholder="请选择安装时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="deviceForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deviceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDeviceSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 远程控制对话框 -->
    <el-dialog
      v-model="remoteControlVisible"
      title="远程控制"
      width="500px"
    >
      <div class="remote-control">
        <el-alert
          title="远程控制功能"
          description="请谨慎使用远程控制功能，操作将直接影响设备运行状态"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px"
        />

        <div class="control-buttons">
          <el-button
            type="primary"
            size="large"
            @click="handleRemoteCommand('open_door')"
          >
            <el-icon><Unlock /></el-icon>
            开启投递口
          </el-button>
          <el-button
            type="warning"
            size="large"
            @click="handleRemoteCommand('close_door')"
          >
            <el-icon><Lock /></el-icon>
            关闭投递口
          </el-button>
          <el-button
            type="success"
            size="large"
            @click="handleRemoteCommand('compress')"
          >
            <el-icon><Operation /></el-icon>
            启动压缩
          </el-button>
          <el-button
            type="info"
            size="large"
            @click="handleRemoteCommand('status_report')"
          >
            <el-icon><Refresh /></el-icon>
            状态上报
          </el-button>
          <el-button
            type="danger"
            size="large"
            @click="handleRemoteCommand('emergency_stop')"
          >
            <el-icon><CircleClose /></el-icon>
            紧急停止
          </el-button>
          <el-button
            type="warning"
            size="large"
            @click="handleRemoteCommand('restart')"
          >
            <el-icon><RefreshRight /></el-icon>
            重启设备
          </el-button>
        </div>
      </div>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Monitor,
  CircleCheck,
  Warning,
  Tools,
  Plus,
  VideoPlay,
  Download,
  Refresh,
  ArrowDown,
  Unlock,
  Lock,
  Operation,
  CircleClose,
  RefreshRight
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import SearchForm from '@/components/SearchForm.vue'
import DataTable from '@/components/DataTable.vue'
import StatCard from '@/components/StatCard.vue'
import DeviceStatus from '@/components/DeviceStatus.vue'
import { useDeviceStore } from '@/stores/device'
import { formatDateTime } from '@/utils'
import { areaApi } from '@/api/area'

const deviceStore = useDeviceStore()

const loading = ref(false)
const submitting = ref(false)
const detailDialogVisible = ref(false)
const deviceDialogVisible = ref(false)
const remoteControlVisible = ref(false)
const isEdit = ref(false)
const currentDevice = ref<any>(null)
const selectedRows = ref<any[]>([])
const deviceFormRef = ref<FormInstance>()

// 区域数据
const areaLoading = ref(false)
const areaOptions = ref<Array<{label: string, value: string}>>([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  type: '',
  location: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 设备统计
const deviceStats = reactive({
  totalCount: 156,
  totalTrend: '+8.5%',
  onlineCount: 142,
  onlineTrend: '+12.3%',
  errorCount: 3,
  errorTrend: '-25.6%',
  maintenanceCount: 11,
  maintenanceTrend: '+5.2%'
})

// 设备列表
const deviceList = ref<any[]>([])

// 设备表单
const deviceForm = reactive({
  name: '',
  code: '',
  type: 'paper',
  location: '',
  maxCapacity: 100,
  status: 'offline',
  installedAt: '',
  remark: ''
})

// 表单验证规则
const deviceRules: FormRules = {
  code: [
    { required: true, message: '请输入设备编号', trigger: 'blur' },
    { pattern: /^[A-Z0-9]{6,20}$/, message: '设备编号格式不正确', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请选择安装地点', trigger: 'change' }
  ],
  maxCapacity: [
    { required: true, message: '请输入最大容量', trigger: 'blur' },
    { type: 'number', min: 1, max: 1000, message: '容量范围在 1 到 1000 kg', trigger: 'blur' }
  ]
}

// 获取设备类型标签
const getTypeTag = (type: string) => {
  switch (type) {
    case 'paper':
      return 'primary'
    case 'textile':
      return 'success'
    case 'mixed':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取设备类型文本
const getTypeText = (type: string) => {
  switch (type) {
    case 'paper':
      return '纸壳类'
    case 'textile':
      return '织物类'
    case 'mixed':
      return '混合类'
    default:
      return '未知类型'
  }
}

// 获取容量百分比
const getCapacityPercentage = (device: any) => {
  return Math.round((device.currentCapacity / device.maxCapacity) * 100)
}

// 获取容量颜色
const getCapacityColor = (device: any) => {
  const percentage = getCapacityPercentage(device)
  if (percentage >= 90) return '#F56C6C'
  if (percentage >= 70) return '#E6A23C'
  return '#67C23A'
}

// 加载区域数据
const loadAreaOptions = async () => {
  areaLoading.value = true
  try {
    const response = await areaApi.getAreaTree()
    // 将区域数据转换为下拉选项格式
    const flattenAreas = (areas: any[], prefix = '') => {
      let options: Array<{label: string, value: string}> = []
      areas.forEach(area => {
        const label = prefix ? `${prefix} / ${area.name}` : area.name
        options.push({
          label,
          value: area.name
        })
        if (area.children && area.children.length > 0) {
          options = options.concat(flattenAreas(area.children, label))
        }
      })
      return options
    }
    areaOptions.value = flattenAreas(response.data.list)
  } catch (error) {
    ElMessage.error('加载区域数据失败')
  } finally {
    areaLoading.value = false
  }
}

// 加载设备列表
const loadDeviceList = async () => {
  loading.value = true
  try {
    // 模拟演示数据
    const mockDeviceList = [
      {
        id: 1,
        name: '纸壳回收箱-001',
        code: 'HF001001',
        type: 'paper',
        status: 'online',
        location: '合肥市经开区翡翠湖畔小区1号楼下',
        currentCapacity: 45,
        maxCapacity: 100,
        todayDisposals: 12,
        totalDisposals: 1580,
        installedAt: '2024-01-15 09:00:00',
        lastReportAt: '2024-01-27 21:45:00',
        todayEarnings: '68.50',
        totalEarnings: '8520.30'
      },
      {
        id: 2,
        name: '织物回收箱-002',
        code: 'HF001002',
        type: 'textile',
        status: 'online',
        location: '合肥市经开区翡翠湖畔小区2号楼下',
        currentCapacity: 78,
        maxCapacity: 150,
        todayDisposals: 8,
        totalDisposals: 956,
        installedAt: '2024-01-20 14:30:00',
        lastReportAt: '2024-01-27 21:30:00',
        todayEarnings: '42.80',
        totalEarnings: '5680.90'
      },
      {
        id: 3,
        name: '混合回收箱-003',
        code: 'HF001003',
        type: 'mixed',
        status: 'full',
        location: '合肥市经开区翡翠湖畔小区3号楼下',
        currentCapacity: 95,
        maxCapacity: 100,
        todayDisposals: 15,
        totalDisposals: 2150,
        installedAt: '2024-01-10 11:00:00',
        lastReportAt: '2024-01-27 20:15:00',
        todayEarnings: '89.20',
        totalEarnings: '12580.50'
      },
      {
        id: 4,
        name: '纸壳回收箱-004',
        code: 'HF001004',
        type: 'paper',
        status: 'offline',
        location: '合肥市经开区翡翠湖畔小区4号楼下',
        currentCapacity: 25,
        maxCapacity: 100,
        todayDisposals: 0,
        totalDisposals: 680,
        installedAt: '2024-02-01 16:00:00',
        lastReportAt: '2024-01-27 18:30:00',
        todayEarnings: '0.00',
        totalEarnings: '3250.80'
      },
      {
        id: 5,
        name: '织物回收箱-005',
        code: 'HF001005',
        type: 'textile',
        status: 'maintenance',
        location: '合肥市经开区翡翠湖畔小区5号楼下',
        currentCapacity: 0,
        maxCapacity: 150,
        todayDisposals: 0,
        totalDisposals: 1250,
        installedAt: '2024-01-25 10:30:00',
        lastReportAt: '2024-01-27 15:00:00',
        todayEarnings: '0.00',
        totalEarnings: '7890.60'
      },
      {
        id: 6,
        name: '混合回收箱-006',
        code: 'HF001006',
        type: 'mixed',
        status: 'online',
        location: '合肥市经开区翡翠湖畔小区商业街入口',
        currentCapacity: 62,
        maxCapacity: 120,
        todayDisposals: 18,
        totalDisposals: 1890,
        installedAt: '2024-01-12 13:45:00',
        lastReportAt: '2024-01-27 21:50:00',
        todayEarnings: '95.40',
        totalEarnings: '9850.20'
      },
      {
        id: 7,
        name: '纸壳回收箱-007',
        code: 'HF001007',
        type: 'paper',
        status: 'online',
        location: '合肥市经开区翡翠湖畔小区地下车库入口',
        currentCapacity: 38,
        maxCapacity: 80,
        todayDisposals: 9,
        totalDisposals: 1120,
        installedAt: '2024-01-18 08:20:00',
        lastReportAt: '2024-01-27 21:20:00',
        todayEarnings: '52.60',
        totalEarnings: '6420.40'
      },
      {
        id: 8,
        name: '织物回收箱-008',
        code: 'HF001008',
        type: 'textile',
        status: 'error',
        location: '合肥市经开区翡翠湖畔小区健身区',
        currentCapacity: 15,
        maxCapacity: 100,
        todayDisposals: 2,
        totalDisposals: 450,
        installedAt: '2024-02-05 15:10:00',
        lastReportAt: '2024-01-27 12:30:00',
        todayEarnings: '8.50',
        totalEarnings: '2180.90'
      }
    ]

    // 模拟分页和搜索
    let filteredList = mockDeviceList

    // 应用搜索过滤
    if (searchForm.keyword) {
      filteredList = filteredList.filter(device =>
        device.name.includes(searchForm.keyword) ||
        device.code.includes(searchForm.keyword)
      )
    }

    if (searchForm.status) {
      filteredList = filteredList.filter(device => device.status === searchForm.status)
    }

    if (searchForm.type) {
      filteredList = filteredList.filter(device => device.type === searchForm.type)
    }

    if (searchForm.location) {
      filteredList = filteredList.filter(device =>
        device.location.includes(searchForm.location)
      )
    }

    // 模拟分页
    const startIndex = (pagination.page - 1) * pagination.size
    const endIndex = startIndex + pagination.size
    const paginatedList = filteredList.slice(startIndex, endIndex)

    deviceList.value = paginatedList
    pagination.total = filteredList.length

    // 更新统计数据
    deviceStats.totalCount = mockDeviceList.length
    deviceStats.onlineCount = mockDeviceList.filter(d => d.status === 'online').length
    deviceStats.errorCount = mockDeviceList.filter(d => d.status === 'error').length
    deviceStats.maintenanceCount = mockDeviceList.filter(d => d.status === 'maintenance').length

  } catch (error) {
    ElMessage.error('加载设备列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadDeviceList()
}

// 重置处理
const handleReset = () => {
  pagination.page = 1
  loadDeviceList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadDeviceList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadDeviceList()
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 新增设备
const handleAddDevice = () => {
  isEdit.value = false
  Object.assign(deviceForm, {
    name: '',
    code: '',
    type: 'paper',
    location: '',
    maxCapacity: 100,
    status: 'offline',
    installedAt: '',
    remark: ''
  })
  deviceDialogVisible.value = true
}

// 编辑设备
const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(deviceForm, row)
  deviceDialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row: any) => {
  // 模拟获取设备详细信息
  currentDevice.value = {
    ...row,
    todayEarnings: '156.80',
    totalEarnings: '12580.50',
    errorCount: 2,
    maintenanceCount: 5,
    rating: 4.5,
    temperature: 25,
    humidity: 65,
    batteryLevel: 85,
    signalStrength: -65,
    recentDisposals: [
      {
        id: 1001,
        userName: '张三',
        wasteType: '塑料',
        weight: 2.5,
        earnings: 5.20,
        createdAt: '2024-01-15 14:30:00',
        status: 'success'
      },
      {
        id: 1002,
        userName: '李四',
        wasteType: '纸类',
        weight: 1.8,
        earnings: 3.60,
        createdAt: '2024-01-15 13:20:00',
        status: 'success'
      }
    ]
  }
  detailDialogVisible.value = true
}

// 设备表单提交
const handleDeviceSubmit = async () => {
  if (!deviceFormRef.value) return

  try {
    await deviceFormRef.value.validate()
    submitting.value = true

    // 调用创建/更新设备API
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    deviceDialogVisible.value = false
    loadDeviceList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

// 批量上线
const handleBatchOnline = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedRows.value.length} 台设备设置为在线状态吗？`,
      '批量上线',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用批量上线API
    ElMessage.success('批量上线成功')
    loadDeviceList()
  } catch (error) {
    // 用户取消
  }
}

// 批量维护
const handleBatchMaintenance = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedRows.value.length} 台设备设置为维护状态吗？`,
      '批量维护',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用批量维护API
    ElMessage.success('批量设置维护成功')
    loadDeviceList()
  } catch (error) {
    // 用户取消
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 远程控制命令
const handleRemoteCommand = async (command: string) => {
  try {
    const commandText = {
      open_door: '开启投递口',
      close_door: '关闭投递口',
      compress: '启动压缩',
      status_report: '状态上报',
      emergency_stop: '紧急停止',
      restart: '重启设备'
    }[command] || command

    await ElMessageBox.confirm(
      `确定要执行"${commandText}"操作吗？`,
      '远程控制确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用远程控制API
    ElMessage.success(`${commandText}命令已发送`)
    remoteControlVisible.value = false
  } catch (error) {
    // 用户取消
  }
}

// 更多操作
const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'remote-control':
      currentDevice.value = row
      remoteControlVisible.value = true
      break
    case 'maintenance':
      ElMessage.info('维护记录功能开发中...')
      break
    case 'disposal-records':
      ElMessage.info('投递记录功能开发中...')
      break
    case 'clear-bin':
      ElMessage.info('清空回收箱功能开发中...')
      break
    case 'delete':
      ElMessage.info('删除设备功能开发中...')
      break
  }
}

onMounted(() => {
  loadDeviceList()
  loadAreaOptions()
})
</script>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.device-info {
  .device-name {
    font-weight: 600;
    margin-bottom: 4px;
  }

  .device-code {
    font-size: 12px;
    color: #909399;
  }
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.capacity-info {
  .capacity-text {
    font-size: 12px;
    margin-bottom: 4px;
    text-align: center;
  }
}

.device-detail {
  .sensor-data {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }
  }

  .sensor-card {
    text-align: center;

    .sensor-item {
      .sensor-label {
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;
      }

      .sensor-value {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .recent-disposals {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }
  }
}

.remote-control {
  .control-buttons {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;

    .el-button {
      height: 60px;
      font-size: 14px;

      .el-icon {
        margin-right: 8px;
        font-size: 18px;
      }
    }
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }

  .remote-control {
    .control-buttons {
      grid-template-columns: 1fr;
    }
  }
}
</style>
